/* eslint-disable import/no-dynamic-require */
/* eslint-disable import/no-unresolved */
/* eslint-disable import/extensions */
/* eslint-disable prefer-destructuring */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable global-require */
/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable no-empty */
/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable promise/catch-or-return */
/* eslint-disable promise/always-return */
/* eslint-disable eqeqeq */
/* eslint-disable no-nested-ternary */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable no-undef */
/* eslint-disable no-alert */
import { Button, LinearProgress } from '@mui/material';
import React, { useState, useEffect, useMemo } from 'react';
import {
  ClockCircleFilled,
  PlusOutlined,
  SearchOutlined,
  DeleteFilled,
  GithubFilled,
  ArrowLeftOutlined,
  CheckCircleFilled,
  MinusCircleFilled,
} from '@ant-design/icons';
import IconFont from '@/renderer/components/IconFont';
import Typography from '@mui/material/Typography';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAsyncEffect, useRequest } from 'ahooks';
import Box from '@mui/material/Box';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import ListSubheader from '@mui/material/ListSubheader';
import Divider from '@mui/material/Divider';
import { PhotoProvider, PhotoView } from 'react-photo-view';
import Modal from '@/renderer/components/Modal';
import UploadFile from '@/renderer/components/UploadAvatar';
import TextField from '@mui/material/TextField';
import 'react-photo-view/dist/react-photo-view.css';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Grid from '@mui/material/Grid';
import dayjs from 'dayjs';
import Popover from '@mui/material/Popover';
import { green } from '@mui/material/colors';
import { ipcRenderer } from 'electron';
import { useIdb } from 'react-use-idb';
import fs from 'fs';
import { useDispatch } from 'react-redux';
import { change } from '@/renderer/store/snackbar';

const url = '/webtool/v1/project';
const userurl = '/webtool/v1/user';

const roletype = {
  1: '产品',
  2: '前端',
  3: '后端',
  4: '测试',
};
const userlist = [
  {
    id: 1,
    name: '徐涛',
    user_name: 'xutao',
    password: '123456',
    role_type: '1',
    age: null,
  },
  {
    id: 2,
    name: '左玲玲',
    user_name: 'zuolingling',
    password: '123456',
    role_type: '2',
    age: null,
  },
  {
    id: 3,
    name: '王静',
    user_name: 'wangjing',
    password: '123456',
    role_type: '4',
    age: null,
  },
  {
    id: 4,
    name: '李国才',
    user_name: 'liguocai',
    password: '123456',
    role_type: '3',
    age: null,
  },
];

function decodeBase64Image(dataString) {
  const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
  const response = {};

  if (matches.length !== 3) {
    return new Error('Invalid input string');
  }

  response.type = matches[1];
  response.data = Buffer.from(matches[2], 'base64');

  return response;
}

function ProjectSetting() {
  const navigate = useNavigate();
  const [modalprops, setmodal] = useState({
    open: false,
    submit: {},
    reload: false,
  });
  const [popover, setpopover] = useState({
    open: false,
    anchorEl: null,
    onClose: () => {
      setpopover((s) => ({ ...s, open: false }));
    },
  });
  const [localPath, setlocalPath] = useState(null);
  const [value, setValue] = useIdb('projects');
  const [data, setdata] = useState();
  const dispatch = useDispatch();

  const {
    state: { id },
  } = useLocation();

  async function getSettings(path) {
    // columns获取
    const readres = await fs.readFileSync(path, 'utf8');
    if (readres) {
      const re = /{[\S\s]*}/;
      const match = readres.match(re);
      try {
        const resdata = JSON.parse(match[0]);
        setdata((s) => {
          return {
            ...s,
            ...resdata,
          };
        });
      } catch (error) {
        dispatch(
          change({
            open: true,
            message: 'Settings对象需以JSON格式编写!',
            severity: 'error',
          })
        );
      }
    }
  }

  useAsyncEffect(async () => {
    const curdata = value ? value?.filter((it) => it.id == id)[0] : {};
    let path = null;
    if (curdata?.project_name) {
      path = localStorage.getItem(curdata?.project_name) ?? null;
      setlocalPath(path);
    }
    await setdata(curdata);
    if (!path) return;
    const paths = `${path}/config/defaultSettings.js`;
    await getSettings(paths);
  }, [value, localPath]);

  const columns = [
    {
      title: '项目logo',
      dataIndex: 'logo_url',
      icon: 'icon-fenlei',
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
      icon: 'icon-tags',
    },
    {
      title: '项目地址',
      dataIndex: 'project_address',
      icon: 'icon-github-fill',
    },
    {
      title: '项目备案信息',
      dataIndex: 'put_on_record',
      icon: 'icon-dunpai1',
    },
    {
      title: '截止日期',
      icon: 'icon-icon-time',
      dataIndex: 'deadline',
    },
  ];

  const columnes = [
    {
      title: '代理字符',
      dataIndex: 'proxypath',
      icon: 'icon-Nginx',
    },
    {
      title: '打包名称',
      dataIndex: 'output_path',
      icon: 'icon-package-fill',
    },
    {
      title: '开发环境',
      dataIndex: 'dev_env',
      icon: 'icon-dev',
    },
    {
      title: '测试环境',
      dataIndex: 'test_env',
      icon: 'icon-biz-test',
    },
    {
      title: '生产环境',
      dataIndex: 'pro_env',
      icon: 'icon-shangchuan',
    },
  ];

  async function handleitemclick(it) {
    await setmodal((s) => ({
      ...s,
      submit: data,
    }));
    setmodal((s) => ({
      ...s,
      open: true,
      title: `修改${it.title}`,
      dataIndex: it.dataIndex,
    }));
  }

  const curusers = data?.project_users ? JSON.parse(data?.project_users) : [];

  useEffect(() => {
    if (data?.project_name) {
    }
  }, [data?.project_name]);

  function updateKeys(key, val) {
    const newvalue = value?.map?.((it, i) => {
      if (it.id == id) {
        return {
          ...it,
          [key]: val,
        };
      }
      return it;
    });
    setValue(newvalue);
  }

  return (
    <div
      style={{
        width: '100%',
        position: 'absolute',
        height: '100%',
      }}
    >
      <PhotoProvider>
        <div style={{ margin: 12 }}>
          <div
            className="centerl"
            style={{
              marginBottom: 12,
              justifyContent: 'space-between',
              userSelect: 'none',
              cursor: 'pointer',
            }}
          >
            <div
              className="centerl"
              onClick={() => {
                navigate(-1);
              }}
            >
              <ArrowLeftOutlined
                style={{
                  color: 'rgba(255,255,255,0.8)',
                  fontSize: 20,
                  margin: '-3px 6px 0 0',
                }}
              />
              <Typography variant="h6" color="rgba(255,255,255,0.8)" mr={2}>
                项目设置
              </Typography>
            </div>
            <div
              className="center"
              style={{ cursor: 'pointer', color: '#999999' }}
              onClick={() => {}}
            >
              <ClockCircleFilled
                rotate={0}
                style={{ marginRight: 8, fontSize: 14 }}
              />
              <span>{dayjs(data?.created_at).format('YYYY/MM/DD HH:mm')}</span>
            </div>
          </div>
        </div>
        <Grid container spacing={2}>
          <Grid item xs={8}>
            <Box
              sx={{
                width: '100%',
                bgcolor: '#666666',
                borderRadius: 3,
                overflow: 'hidden',
              }}
            >
              <nav aria-label="main mailbox folders">
                <List
                  subheader={
                    <ListSubheader
                      component="div"
                      id="nested-list-subheader"
                      style={{ backgroundColor: '#666666' }}
                    >
                      <span style={{ fontSize: 18, color: '#ffffff' }}>
                        基础信息
                      </span>
                    </ListSubheader>
                  }
                >
                  {columns.map((it, i) => {
                    return (
                      <ListItem
                        onClick={async () => {
                          await handleitemclick(it);
                        }}
                        key={it.dataIndex}
                        disablePadding
                        secondaryAction={
                          <div onClick={(e) => e.stopPropagation()}>
                            {it.dataIndex === 'logo_url' ? (
                              <PhotoView src={data && data[it.dataIndex]}>
                                <img
                                  src={data && data[it.dataIndex]}
                                  style={{ width: 30, height: 30 }}
                                  alt=""
                                />
                              </PhotoView>
                            ) : it.dataIndex === 'project_address' ? (
                              <a
                                style={{
                                  color: 'rgba(255,255,255,1)',
                                  margin: 0,
                                }}
                                href={data && data[it.dataIndex]}
                                target="_blank"
                                rel="noreferrer"
                                className="oneline"
                              >
                                {data && data[it.dataIndex]}
                              </a>
                            ) : it.dataIndex === 'deadline' ? (
                              <span
                                style={{ display: 'block' }}
                                className="oneline"
                              >
                                {data?.deadline &&
                                  dayjs(data[it.dataIndex]).format(
                                    'YYYY/MM/DD'
                                  )}
                              </span>
                            ) : (
                              <span
                                style={{ display: 'block' }}
                                className="oneline"
                              >
                                {data && data[it.dataIndex]}
                              </span>
                            )}
                          </div>
                        }
                      >
                        <ListItemButton>
                          <ListItemIcon>
                            <IconFont
                              type={it.icon}
                              style={{ color: '#999999' }}
                            />
                          </ListItemIcon>
                          <ListItemText primary={it.title} />
                        </ListItemButton>
                      </ListItem>
                    );
                  })}
                </List>
              </nav>
            </Box>
          </Grid>
          <Grid item xs={4}>
            <Box
              sx={{
                width: '100%',
                bgcolor: '#444444',
                borderRadius: 3,
                overflow: 'hidden',
              }}
            >
              <nav aria-label="main mailbox folders">
                <List
                  subheader={
                    <ListSubheader
                      component="div"
                      id="nested-list-subheader"
                      style={{ backgroundColor: '#444444' }}
                    >
                      <span style={{ fontSize: 18, color: '#ffffff' }}>
                        发布信息
                      </span>
                    </ListSubheader>
                  }
                >
                  {columnes.map((it, i) => {
                    return (
                      <ListItem
                        onClick={async () => {
                          await handleitemclick(it);
                        }}
                        key={it.dataIndex}
                        disablePadding
                        secondaryAction={
                          <div onClick={(e) => e.stopPropagation()}>
                            {it.dataIndex === 'logo_url' ? (
                              <PhotoView src={data && data[it.dataIndex]}>
                                <img
                                  src={data && data[it.dataIndex]}
                                  style={{ width: 30, height: 30 }}
                                  alt=""
                                />
                              </PhotoView>
                            ) : it.dataIndex === 'project_address' ? (
                              <a
                                style={{
                                  color: 'rgba(255,255,255,1)',
                                  margin: 0,
                                }}
                                href={data && data[it.dataIndex]}
                                target="_blank"
                                rel="noreferrer"
                              >
                                {data && data[it.dataIndex]}
                              </a>
                            ) : it.dataIndex === 'deadline' ? (
                              <span style={{ display: 'block' }}>
                                {data &&
                                  dayjs(data[it.dataIndex]).format(
                                    'YYYY/MM/DD'
                                  )}
                              </span>
                            ) : (
                              <span style={{ display: 'block' }}>
                                {data && data[it.dataIndex]}
                              </span>
                            )}
                          </div>
                        }
                      >
                        <ListItemButton>
                          <ListItemIcon>
                            <IconFont
                              type={it.icon}
                              style={{ color: '#999999', fontSize: 18 }}
                            />
                          </ListItemIcon>
                          <ListItemText primary={it.title} />
                        </ListItemButton>
                      </ListItem>
                    );
                  })}
                </List>
              </nav>
            </Box>
          </Grid>
          <Grid item xs={4}>
            <Box
              sx={{
                width: '100%',
                bgcolor: '#666666',
                borderRadius: 3,
                overflow: 'hidden',
              }}
            >
              <nav aria-label="main mailbox folders">
                <List
                  subheader={
                    <ListSubheader
                      component="div"
                      id="nested-list-subheader"
                      style={{ backgroundColor: '#666666' }}
                    >
                      <span style={{ fontSize: 18, color: '#ffffff' }}>
                        参与人员
                      </span>
                    </ListSubheader>
                  }
                >
                  {userlist?.map((it, i) => {
                    return (
                      <ListItem
                        onClick={async () => {
                          let submituser = [];
                          if (curusers.some((item) => item.id == it.id)) {
                            submituser = curusers.filter(
                              (item) => item.id != it.id
                            );
                          } else {
                            submituser = [...curusers, it];
                          }
                          // 更新
                          updateKeys(
                            'project_users',
                            JSON.stringify(submituser)
                          );
                        }}
                        key={it.id}
                        disablePadding
                        secondaryAction={
                          <div onClick={(e) => e.stopPropagation()}>
                            {roletype[it.role_type]}
                          </div>
                        }
                      >
                        <ListItemButton>
                          <ListItemIcon>
                            {curusers.some((item) => item.id == it.id) ? (
                              <CheckCircleFilled
                                style={{ color: green[400], fontSize: 18 }}
                              />
                            ) : (
                              <MinusCircleFilled
                                style={{ color: '#999999', fontSize: 18 }}
                              />
                            )}
                          </ListItemIcon>
                          <ListItemText primary={it.name} />
                        </ListItemButton>
                      </ListItem>
                    );
                  })}
                </List>
              </nav>
            </Box>
          </Grid>
          <Grid item xs={8}>
            <Box
              sx={{
                bgcolor: '#444444',
                borderRadius: 3,
                overflow: 'hidden',
                padding: '24px',
                minHeight: 200,
                background: `url(${require('@/renderer/assets/site.jpg')}) no-repeat center`,
                backgroundSize: 'cover',
                display: 'flex',
                justifyContent: 'space-around',
                alignItems: 'center',
              }}
            >
              <Button
                style={{
                  flex: 1,
                  height: 200,
                  color: '#aaaaaa',
                  fontSize: 18,
                }}
                onClick={() => {
                  ipcRenderer.send('save_path', data);
                }}
              >
                初始化项目
              </Button>
              <Button
                style={{
                  flex: 1,
                  fontSize: 18,
                  height: 200,
                  margin: '0 14px',
                  color: '#eeeeee',
                }}
                onClick={() => {
                  navigate('/home/webdevloper', {
                    replace: false,
                    state: { id },
                  });
                }}
              >
                打开项目
              </Button>
              <Button
                style={{ flex: 1, fontSize: 18, height: 200 }}
                color="error"
                onClick={async (e) => {
                  await setpopover((s) => ({
                    ...s,
                    open: true,
                    anchorEl: e.currentTarget,
                  }));
                }}
              >
                删除项目
              </Button>
            </Box>
          </Grid>
          <Grid item xs={12}>
            <Box
              sx={{
                bgcolor: '#444444',
                borderRadius: 3,
                overflow: 'hidden',
                padding: '24px',
                minHeight: 100,
                background: `url(${require('@/renderer/assets/site.jpg')}) no-repeat center`,
                backgroundSize: 'cover',
                display: 'flex',
                justifyContent: 'space-around',
                alignItems: 'center',
              }}
            >
              <div
                style={{
                  width: '100%',
                  heigth: '100%',
                  overflow: 'hidden',
                  borderRadius: 8,
                }}
              >
                <Button
                  style={{
                    width: '100%',
                    height: 100,
                    color: '#aaaaaa',
                    fontSize: 20,
                  }}
                  color="warning"
                  onClick={async () => {
                    if (!localPath) {
                      dispatch(
                        change({
                          open: true,
                          message: '请先初始化项目!',
                          severity: 'error',
                        })
                      );
                    } else {
                      const path = `${localPath}/config/defaultSettings.js`;
                      const picpath = `${localPath}/public/logo.png`;
                      const imageBuffer = decodeBase64Image(data?.logo_url);
                      await fs.writeFileSync(
                        picpath,
                        imageBuffer?.data,
                        (err) => {
                          if (err) {
                            dispatch(
                              change({
                                open: true,
                                message: 'logo写入失败!',
                                severity: 'error',
                              })
                            );
                          }
                        }
                      );

                      const datas = `const Settings = {
name: '${data?.project_name}',
navTheme: 'dark',
primaryColor: '#1890ff',
layout: 'side',
contentWidth: 'Fluid',
fixedHeader: false,
fixSiderbar: false,
pwa: false,
logo: './logo.png',
colorPrimary: '#1890ff',
siderMenuType: 'sub',
proxypath: '/${data?.proxypath}',
put_on_record:'${data?.put_on_record}',
output_path:'${data?.output_path}',
dev_env:'${data?.dev_env}',
test_env:'${data?.test_env}',
pro_env:'${data?.pro_env}',
};
export default Settings;
`;

                      fs.writeFile(path, datas, 'utf8', (error) => {
                        if (error) {
                          dispatch(
                            change({
                              open: true,
                              message: '配置文件写入失败!',
                              severity: 'error',
                            })
                          );
                          return;
                        }
                        dispatch(
                          change({
                            open: true,
                            message: '配置文件写入成功!',
                            severity: 'success',
                          })
                        );
                      });
                    }
                  }}
                >
                  写入文件
                </Button>
              </div>
            </Box>
          </Grid>
        </Grid>
      </PhotoProvider>
      <Popover
        id={id}
        {...popover}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        transformOrigin={{
          horizontal: 'left',
        }}
      >
        <Typography sx={{ p: 2, backgroundColor: '#666666' }}>
          仅删除项目配置,不会删除项目文件{' '}
          <a
            style={{ color: '#ffffff', cursor: 'pointer' }}
            onClick={(e) => {
              const newvalue = value.filter((it) => it.id != id);
              setValue(newvalue);
              localStorage.removeItem(data?.project_name);
              navigate(-1);
            }}
          >
            删除
          </a>
        </Typography>
      </Popover>

      <Modal
        {...modalprops}
        onClose={() => {
          setmodal((s) => ({
            ...s,
            open: false,
          }));
        }}
        onOk={() => {
          updateKeys(
            modalprops.dataIndex,
            modalprops?.submit[modalprops.dataIndex]
          );
          setmodal((s) => ({
            open: false,
          }));
        }}
      >
        {modalprops?.dataIndex == 'logo_url' ? (
          <UploadFile
            value={modalprops?.submit?.logo_url}
            onChange={(val) => {
              setmodal((s) => ({
                ...s,
                submit: {
                  ...s.submit,
                  logo_url: val,
                },
              }));
            }}
          />
        ) : modalprops?.dataIndex == 'deadline' ? (
          <LocalizationProvider
            dateAdapter={AdapterDayjs}
            adapterLocale="zh_cn"
          >
            <DatePicker
              label="选择日期"
              inputFormat="YYYY/MM/DD"
              fullWidth
              value={
                modalprops?.submit
                  ? modalprops?.submit[modalprops.dataIndex]
                  : new Date()
              }
              onChange={(value) => {
                setmodal((s) => ({
                  ...s,
                  submit: {
                    ...s.submit,
                    [modalprops.dataIndex]: dayjs(value).format('YYYY-MM-DD'),
                  },
                }));
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  fullWidth
                  style={{ margin: '12px 0 18px 0' }}
                />
              )}
            />
          </LocalizationProvider>
        ) : (
          <TextField
            fullWidth
            id="outlined-basic"
            label="请输入"
            variant="outlined"
            value={
              modalprops?.submit && modalprops?.submit[modalprops.dataIndex]
            }
            style={{ margin: '12px 0 18px 0' }}
            onChange={(e) => {
              setmodal((s) => ({
                ...s,
                submit: {
                  ...s.submit,
                  [modalprops.dataIndex]: e.target.value,
                },
              }));
            }}
          />
        )}
      </Modal>
    </div>
  );
}

export default ProjectSetting;
